package com.qianbao.qianbaobusiness.ui.cashier.databill;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.androidbase.utils.StatusBarHelper;
import com.androidbase.utils.ToastUtils;
import com.qianbao.qianbaobusiness.R;
import com.qianbao.qianbaobusiness.json.DayBillDetailedBean;
import com.qianbao.qianbaobusiness.json.FeedBackTagBean;
import com.qianbao.qianbaobusiness.ui.cashier.BillingDetailsActivity;
import com.qianbao.qianbaobusiness.ui.cashier.databill.dialog.WheelPickerDialog;
import com.qianbao.qianbaobusiness.ui.help.FeedBackActivity;
import com.qianbao.qianbaobusiness.ui.widget.RiseNumberTextView;
import com.qianbao.qianbaobusiness.ui.widget.calendar.view.DatePickerDialog;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class DataBillOldActivity extends BaseScrollviewFreshActivity implements BillsDetailsRequest {

    private List<DayBillClassificationBean> classificationList = new ArrayList<>();
    private List<DayBillDetailedBean> detaileList = new ArrayList<>();
    private List<String> listStr = new ArrayList<>();

    private TextView calendarTv;
    private TextView calendarNumberTv;
    private RiseNumberTextView calendarAmountTv;
    private TextView calendarTimeTv;
    private TextView calendarScreenTv, billClassificationTv, billDetailsTv;
    private RecyclerView calendarClassificationRv;
    private RecyclerView calendarScreenRv;

    private CustomDialog customDialog;
    private BillsDetailsModelImpl billsDetailsModel;
    private DataBillAdapter dataBillAdapter;
    private String chkAccountDate;//账单日期
    private int type = 0;// 对账渠道类型
    private int pageNum = 1;// 页码
    private int pageSize = 10;// 每页条数
    private DataBillDetailedAdapter billDetailedAdapter;

    private boolean pullRefresh = false;
    private TextView textView;
    private TextView calendarQuestionsTv;
    private LinearLayout layout_empty;
    private String postMerchantNo;

    @Override
    public void setTranslucentStatus() {
        StatusBarHelper.translateStatusBar(this);
    }

    @Override
    protected void initToolBar() {
        setToolBarTitle("日账单");
        setToolBarTitleColor(R.color.c_4a4a4a);
        setToolBarBackgroundColor(R.color.app_white);
        setNavigationIcon(R.drawable.icon_toolbar_back);

        showRightIcon();
        setRightIcon(R.mipmap.calendar_back_icon);

        setPullDownEnabled(false);
    }

    @Override
    protected void initView() {
        View inflate = LayoutInflater.from(DataBillOldActivity.this)
                .inflate(R.layout.activity_data_bill_old, null);
        calendarTv = (TextView) inflate.findViewById(R.id.data_bill_calendar_tv);
        calendarNumberTv = (TextView) inflate.findViewById(R.id.data_bill_calendar_number_tv);
        calendarAmountTv = (RiseNumberTextView) inflate.findViewById(R.id.data_bill_calendar_amount_tv);
        calendarTimeTv = (TextView) inflate.findViewById(R.id.data_bill_calendar_time_tv);
        calendarQuestionsTv = (TextView) inflate.findViewById(R.id.data_bill_questions_tv);
        calendarQuestionsTv.setOnClickListener(this);
        calendarScreenTv = (TextView) inflate.findViewById(R.id.data_bill_screen_tv);

        billClassificationTv = (TextView) inflate.findViewById(R.id.data_bill_classification_tv);
        billDetailsTv = (TextView) inflate.findViewById(R.id.data_bill_details_tv);
        layout_empty = (LinearLayout) inflate.findViewById(R.id.layout_empty);

        calendarClassificationRv = (RecyclerView) inflate.findViewById(R.id.data_bill_classification_rv);
        calendarScreenRv = (RecyclerView) inflate.findViewById(R.id.data_bill_screen_rv);
        scrollView.addView(inflate);

        billClassificationTv.setOnClickListener(this);
        billDetailsTv.setOnClickListener(this);
        calendarScreenTv.setOnClickListener(this);

        setLineView(true);
        initEmptyLayout();
        Intent intent = getIntent();
        chkAccountDate = intent.getStringExtra("chkAccountDate");
        postMerchantNo = intent.getStringExtra("postMerchantNo");
        billsDetailsModel = new BillsDetailsModelImpl(this, this);
        billsDetailsModel.getQueryDayChecking(chkAccountDate, postMerchantNo);
        billsDetailsModel.getQueryTradeDetailPage(chkAccountDate, postMerchantNo, type, pageNum, pageSize);

        setTextData(null);
        setClassificationAdapter();
        setDetaileAdapter();

        getListStr();

    }

    private void setTextData(DayBillClassificationBean classificationBean) {
        if (classificationBean != null) {
            if (classificationBean.getChkAccountType() == 0) {
                String changeTime1 = FormatUtil.changeTime1(classificationBean.getChkAccountDate(), "yyyy-MM-dd");
                calendarTv.setText(changeTime1 + "  账单");
                calendarNumberTv.setText("共" + classificationBean.getAccountNum() + "笔");
                String settlementAmt = Double.parseDouble(classificationBean.getSettlementAmtTotal() + "") / 100 + "";
                calendarAmountTv.setText(getResources().getString(R.string.rmb) + FormatUtil
                        .getMoneyFormat(settlementAmt));
                String changeTime2 = FormatUtil.changeTime1(classificationBean.getSettleDate(), "yyyy-MM-dd");
                calendarTimeTv.setText("预计" + changeTime2 + "  24:00前，款项分多笔到账");
            }
        } else {
            calendarTv.setText("暂无数据");
            calendarNumberTv.setText("暂无数据");
            calendarAmountTv.setText(getResources().getString(R.string.rmb) + "0.00");
            calendarTimeTv.setText("暂无数据");
        }
    }

    private void setClassificationAdapter() {
        if (classificationList != null && classificationList.size() > 0) {
            DayBillClassificationBean dayBillClassificationBean1 = null;
            DayBillClassificationBean dayBillClassificationBean2 = null;
            DayBillClassificationBean dayBillClassificationBean3 = null;
            DayBillClassificationBean dayBillClassificationBean4 = null;
            //1：刷卡支付 2：支付宝 3：微信 4：钱包生活
            dayBillClassificationBean1 = new DayBillClassificationBean(1, 0l, 0, "", "");
            dayBillClassificationBean2 = new DayBillClassificationBean(3, 0l, 0, "", "");
            dayBillClassificationBean3 = new DayBillClassificationBean(2, 0l, 0, "", "");
            dayBillClassificationBean4 = new DayBillClassificationBean(4, 0l, 0, "", "");

            for (int i = 0; i < classificationList.size(); i++) {
                if (classificationList.get(i).getChkAccountType() == 1) {
                    dayBillClassificationBean1 = classificationList.get(i);
                } else if (classificationList.get(i).getChkAccountType() == 3) {
                    dayBillClassificationBean2 = classificationList.get(i);
                } else if (classificationList.get(i).getChkAccountType() == 2) {
                    dayBillClassificationBean3 = classificationList.get(i);
                } else if (classificationList.get(i).getChkAccountType() == 4) {
                    dayBillClassificationBean4 = classificationList.get(i);
                }
            }
            classificationList.clear();
            classificationList.add(dayBillClassificationBean1);
            classificationList.add(dayBillClassificationBean2);
            classificationList.add(dayBillClassificationBean3);
            classificationList.add(dayBillClassificationBean4);

        }

        if (dataBillAdapter == null) {
            dataBillAdapter = new DataBillAdapter(DataBillOldActivity.this, classificationList);
            calendarClassificationRv.setLayoutManager(new LinearLayoutManager(getThis()));
            calendarClassificationRv.setAdapter(dataBillAdapter);
        } else {
            dataBillAdapter.setRefreshAdapter(classificationList);
        }
    }

    private void setDetaileAdapter() {
        if (billDetailedAdapter == null) {
            billDetailedAdapter = new DataBillDetailedAdapter(DataBillOldActivity.this, detaileList);
            calendarScreenRv.setLayoutManager(new LinearLayoutManager(getThis()));
            calendarScreenRv.setAdapter(billDetailedAdapter);
            billDetailedAdapter.setOnItemClickListener(new OnRecyclerViewItemClickListener() {
                @Override
                public void onItemClick(ViewGroup parent, View view, int position) {
                    //修复buglly上的bug110
                    if (detaileList.size() <= position) {
                        return;
                    }
                    DayBillDetailedBean billDetailedBean = detaileList.get(position);
                    Bundle bundle = new Bundle();
                    //                    bundle.putInt("settlementId", billDetailedBean.getSettlementId());
                    //                    bundle.putString("chkAccountDate", chkAccountDate);
                    //                    bundle.putInt("type", billDetailedBean.getChkAccountType());
                    bundle.putSerializable("billDetailedBean", billDetailedBean);
                    Intent intent = new Intent();
                    intent.putExtras(bundle);
                    intent.setClass(DataBillOldActivity.this, BillingDetailsActivity.class);
                    startActivity(intent);
                    //                    JumpManager.gotoActivity(getThis(), BillingDetailsActivity.class, false, bundle);
                }
            });
        } else {
            billDetailedAdapter.setRefreshAdapter(detaileList);
        }
    }

    @Override
    protected void onRefreshFinish() {

    }

    @Override
    protected void onLoadMoreFinish() {
        pullRefresh = true;
        pageNum++;//CommInfo.getInstance().getPosMerchantNo()
        billsDetailsModel.getQueryTradeDetailPage(chkAccountDate, postMerchantNo, type, pageNum, pageSize);
    }

    @Override
    public String getCN() {
        return null;
    }

    @Override
    public void LogoutCallback(boolean islogin) {

    }

    @Override
    public void onCritClick(View v) {
        switch (v.getId()) {
            case R.id.data_bill_classification_tv:
                setCustomDialog("因支付公司原因，部分23点到24点之间的刷卡支付交易将会延迟到下一个工作日结算，敬请谅解!");
                break;

            case R.id.data_bill_details_tv:
                //                setCustomDialog("订单号与POS签购单（小票）上的订单号对应");
                break;

            case R.id.data_bill_screen_tv:
                WheelPickerDialog dialog = new WheelPickerDialog(getThis(), listStr);
                dialog.setDialogMode(WheelPickerDialog.DIALOG_MODE_BOTTOM);
                dialog.show();
                dialog.setDatePickListener(new WheelPickerDialog.OnDatePickListener() {

                    @Override
                    public void onClick(String year) {
                        pullRefresh = false;
                        pageNum = 1;
                        setPullUpEnabled(true);
                        switch (year) {
                            case "全部":
                                type = 0;
                                break;
                            case "刷卡支付":
                                type = 1;
                                break;
                            case "微信支付":
                                type = 3;
                                break;
                            case "支付宝支付":
                                type = 2;
                                break;
                            case "钱包生活买单":
                                type = 4;
                                break;
                        }
                        billsDetailsModel.getQueryTradeDetailPage(chkAccountDate, postMerchantNo, type, pageNum, pageSize);
                    }
                });
                break;

            case R.id.data_bill_questions_tv:
                /*String date = calendarTv.getText().toString().replace(" 账单", "");
                String money = calendarAmountTv.getText().toString().trim();
                date = date.substring(5);
                Bundle b = new Bundle();
                b.putCharSequence("date", date);
                b.putCharSequence("sceneId","1");
                b.putCharSequence("money", money);
                JumpManager.gotoActivity(getThis(), FeedbackActivity.class, false, b);*/
                billsDetailsModel.getFeedBackTagList("1");
                break;

            default:
                break;
        }
    }

    private void getListStr() {
        listStr.add("全部");
        listStr.add("刷卡支付");
        listStr.add("微信支付");
        listStr.add("支付宝支付");
        listStr.add("钱包生活买单");
    }

    private void setCustomDialog(String titleStr) {
        CustomDialog.Builder builder1 = new CustomDialog.Builder(getThis());
        builder1.setTitle(titleStr);
        builder1.setPositiveButton("确定", new DialogClick('q'));
        customDialog = builder1.create();
        customDialog.show();
    }

    DayBillClassificationBean classificationB;

    @Override
    public <T> void onSuccess(int number, T resp) {
        switch (number) {
            case 1:
                if (classificationList != null) {
                    classificationList.clear();
                } else {
                    return;
                }
                List<DayBillClassificationBean> beanList = (List<DayBillClassificationBean>) resp;
                if (beanList != null && beanList.size() != 0) {
                    for (DayBillClassificationBean classification : beanList) {
                        if (null != classification && classification.getChkAccountType() != 0) {
                            if (classification.getChkAccountType() == 3) {
                                classificationB = classification;
                            } else {
                                try {
                                    classificationList.add(classification);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        } else {
                            setTextData(classification);
                        }
                    }
                    if (classificationB != null) {
                        try {
                            classificationList.add(1, classificationB);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                }

                if (classificationList.size() == 0) {
                    emptyLayout.setVisibility(View.VISIBLE);
                } else {
                    emptyLayout.setVisibility(View.GONE);
                    setClassificationAdapter();
                }

                break;

            case 2:
                if (pullRefresh) {
                    stopLoad(false);
                }

                if (!pullRefresh) {
                    if (detaileList != null) {
                        detaileList.clear();
                    } else {
                        return;
                    }
                }
                if (((List<DayBillDetailedBean>) resp).size() < pageSize) {
                    billDetailedAdapter.setType(true);
                    setPullUpEnabled(false);
                } else {
                    billDetailedAdapter.setType(false);

                }
                List<DayBillDetailedBean> detailedBeen = (List<DayBillDetailedBean>) resp;
                if (detailedBeen != null && detailedBeen.size() != 0) {
                    try {
                        detaileList.addAll(detailedBeen);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                } else {
                    if (pageNum == 1) {
                        detaileList.clear();
                    }
                    //                    AssistTool.ToastManager.show(getThis(),"没有支付记录");
                }
                if (detaileList.size() == 0) {
                    layout_empty.setVisibility(View.VISIBLE);
                } else {
                    layout_empty.setVisibility(View.GONE);
                }
                setDetaileAdapter();
                break;
            case 4:
                String date = calendarTv.getText().toString().replace(" 账单", "");
                if (!TextUtils.isEmpty(date) && date.length() < 5) {
                    return;
                }
                date = date.substring(5);
                //                String money = calendarAmountTv.getText().toString().trim();
                FeedBackTagBean feedBackTagBean = (FeedBackTagBean) resp;
                List<FeedBackTagBean.FeedbackTagSceneCfgBean.TagListBean> tagList = feedBackTagBean
                        .getFeedbackTagSceneCfg()
                        .getTagList();
                Bundle b = new Bundle();
                b.putCharSequence("sceneId", "1");
                b.putCharSequence("date", date);
                //                b.putCharSequence("money", money);
                b.putSerializable("tagList", (Serializable) tagList);
                Intent intent = new Intent();
                intent.putExtras(b);
                intent.setClass(DataBillOldActivity.this, FeedBackActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    @Override
    public void onFail(int number) {
        classificationList.clear();
        detaileList.clear();
    }

    class DialogClick implements DialogInterface.OnClickListener {

        char type;

        public DialogClick(char type) {
            this.type = type;
        }

        @Override
        public void onClick(DialogInterface dialog, int which) {
            switch (type) {
                case 'q':
                    customDialog.dismiss();
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    protected boolean isClickable() {
        return false;
    }

    @Override
    protected void subtitleClick() {

    }

    @Override
    protected void titleClick() {

    }

    @Override
    protected void rightClick() {
        DatePickerDialog birthDialog = new DatePickerDialog(DataBillOldActivity.this, chkAccountDate, "DataActivity");
        birthDialog.setDialogMode(DatePickerDialog.DIALOG_MODE_BOTTOM);
        birthDialog.show();
        birthDialog.setDatePickListener(new DatePickerDialog.OnDatePickListener() {

            @Override
            public void onClick(String year, String month, String day) {

                String start_Time = year + "-" + month + "-" + day;
                int timeSize = getTimeSize(start_Time, FormatUtil.getYesterday2());
                int time_2016 = getTimeSize(start_Time, "2017-01-01");
                if (time_2016 < 0) {
                    ToastUtils.showShortToast("只能查询2017年的对账单！");
                    return;
                }
                if (timeSize < -183) {
                    ToastUtils.showShortToast("只能查询半年内的对账单！");
                    return;
                }
                if (timeSize <= 0) {
                    chkAccountDate = year + month + day;
                    textView.setText(year + "-" + month + "-" + day);
                    pullRefresh = false;
                    pageNum = 1;
                    type = 0;
                    setPullUpEnabled(true);
                    billsDetailsModel.getQueryDayChecking(chkAccountDate, postMerchantNo);
                    billsDetailsModel.getQueryTradeDetailPage(chkAccountDate, postMerchantNo, type, pageNum, pageSize);
                } else {
                    ToastUtils.showShortToast("只能查询昨天以前的日对账单！");
                }

            }
        });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        listStr = null;
        classificationList = null;
        detaileList = null;
    }

    void initEmptyLayout() {
        View view = LayoutInflater.from(this).inflate(R.layout.day_balance_empty, null);
        textView = (TextView) view.findViewById(R.id.day_empty_date);
        textView.setText(chkAccountDate);
        emptyLayout.addView(view);
        emptyLayout.setVisibility(View.GONE);
    }


    /**
     * 判断两个时间大小
     * @param startTime
     * @param endTime
     * @return
     */
    private int getTimeSize(String startTime, String endTime) {
        if (TextUtils.isEmpty(startTime) || TextUtils.isEmpty(endTime)) {
            return -1;
        }
        int timeIndex = 0;
        java.text.DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        try {
            c1.setTime(df.parse(startTime));
            c2.setTime(df.parse(endTime));
        } catch (java.text.ParseException e) {
            System.err.println("格式不正确");
        }
        int result = c1.compareTo(c2);
        long cc1 = c1.getTimeInMillis();
        long cc2 = c2.getTimeInMillis();
        if (result != 0) {
            return (int) ((cc1 - cc2) / 1000 / 3600 / 24);
        }
        return result;
    }


}
